package com.youzan.cloud.biz.integral.usercase;
import com.alibaba.fastjson.JSONObject;
import com.youzan.cloud.biz.integral.common.CommandHandler;
import com.youzan.cloud.biz.integral.common.UserCommand;
import com.youzan.cloud.biz.integral.extension.LinkerExtensionPoints;
import com.youzan.cloud.biz.integral.model.PointQueryCmd;
import com.youzan.cloud.component.retry.annotation.Retry;
import com.youzan.cloud.connect.service.sdk.ConnectServiceResponse;
import com.youzan.cloud.connect.service.sdk.exception.ConnectServiceCallException;

import com.youzan.cloud.biz.integral.model.request.PointQueryRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
 * 查询积分case
 * @author wangyuan
 */
@Component
@CommandHandler(responseFor = PointQueryCmd.class)
public class QueryPointUserCase extends AbstractPointUserCase<PointQueryCmd> {
    private static final Logger log = LoggerFactory.getLogger(QueryPointUserCase.class);

    @Override
    public Boolean exec(UserCommand param) throws Exception {
        // force cast
        PointQueryCmd cmd = (PointQueryCmd)param;

        log.info("start exec query point user case, {}", JSONObject.toJSONString(cmd));

        cmd.setStatus(UserCommand.ExecStatus.EXECUTING);

        PointQueryRequest request =  PointQueryRequest.builder()
                .mobile(cmd.getMobile())
                .extendMap(cmd.getExtParams())
                .build();

        // write serials log

        // call connector
        ConnectServiceResponse<?> response = syncQueryPointCaseToOutSystem(cmd.getId(), request);

        if(null == response || !response.isSuccess()) {
            cmd.setStatus(UserCommand.ExecStatus.FAILED);

        } else {
            cmd.setStatus(UserCommand.ExecStatus.DONE);
            cmd.setResult(response.getResponseDTO());

        }
        return true;
    }

    @Retry(bizCase = "QueryPointUserCase", uniqKey = "id")
    public ConnectServiceResponse<?>  syncQueryPointCaseToOutSystem(String id, PointQueryRequest request) throws ConnectServiceCallException {

        log.info("SEND_POINT_QUERY_DATA - {}  started", id);
        // call connector
        ConnectServiceResponse<?> response = callLinker(LinkerExtensionPoints.SEND_POINT_QUERY_DATA, request);
        log.info("SEND_POINT_QUERY_DATA - {} finished, result= {}, {}", id, response.isSuccess(), response.getErrMsg());

        return  response;
    }
}
